<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:socialsecurity:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:socialsecurity:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['system:socialsecurity:import']"
          >导入</el-button
        >
      </el-col>

      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="socialsecurityList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="缴纳项目" align="center" prop="project" />
      <el-table-column label="缴纳方式" align="center" prop="baseNum">
        <template #default="scope">
          <dict-tag :options="jiaona" :value="scope.row.baseNum" />
        </template>
      </el-table-column>
      <el-table-column
        label="公司缴纳比例"
        align="center"
        prop="companyPortion"
      >
        <template #default="scope">
          {{ scope.row.companyPortion
          }}{{
            scope.row.companyPortion &&
            !isNaN(Number(scope.row.companyPortion)) &&
            scope.row.companyPortion !== ""
              ? "%"
              : ""
          }}
        </template>
      </el-table-column>

      <el-table-column label="个人缴纳比例" align="center" prop="personPortion">
        <template #default="scope">
          {{ scope.row.personPortion
          }}{{
            scope.row.personPortion && !isNaN(Number(scope.row.personPortion))
              ? "%"
              : ""
          }}
        </template>
      </el-table-column>
      <el-table-column label="公司缴纳金额" align="center" prop="companyPay" />
      <el-table-column label="个人缴纳金额" align="center" prop="personPay" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:socialsecurity:edit']"
            >修改</el-button
          >
          <!-- <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:socialsecurity:remove']"
            >删除</el-button -->
          <!-- > -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加五险一金设置表对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="socialsecurityRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="缴纳项目" prop="project">
          <el-input v-model="form.project" placeholder="请输入缴纳项目" />
        </el-form-item>
        <el-form-item label="缴纳方式" prop="baseNum">
          <el-select v-model="form.baseNum" placeholder="请选择缴纳方式">
            <!-- 默认缴纳方式为1 -->
            <el-option
              v-for="dict in jiaona"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 如果缴纳方式是按比例缴纳 则显示公司缴纳比例和个人缴纳比例 -->

        <template v-if="form.baseNum == 1">
          <el-form-item label="公司缴纳比例" prop="companyPortion">
            <el-input
              v-model="form.companyPortion"
              placeholder="请输入公司缴纳比例"
            >
              <template #append>%</template>
            </el-input>
          </el-form-item>

          <el-form-item label="个人缴纳比例" prop="personPortion">
            <el-input
              v-model="form.personPortion"
              placeholder="请输入个人缴纳比例"
            >
              <template #append>%</template>
            </el-input>
          </el-form-item>
        </template>

        <!-- 如果缴纳方式是按金额缴纳 则显示公司缴纳金额和个人缴纳金额 -->

        <template v-if="form.baseNum == 2">
          <el-form-item label="公司缴纳金额" prop="companyPay">
            <el-input
              v-model="form.companyPay"
              placeholder="请输入公司缴纳金额"
            >
              <template #prepend>¥</template>
            </el-input>
          </el-form-item>

          <el-form-item label="个人缴纳金额" prop="personPay">
            <el-input v-model="form.personPay" placeholder="请输入个人缴纳金额">
              <template #prepend>¥</template>
            </el-input>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改五险一金设置表对话框 -->
    <el-dialog :title="title" v-model="open1" width="500px" append-to-body>
      <el-form
        ref="socialsecurityRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="缴纳项目" prop="project">
          <el-input
            v-model="form.project"
            placeholder="请输入缴纳项目"
            disabled
          />
        </el-form-item>
        <el-form-item label="缴纳方式" prop="baseNum">
          <el-select v-model="form.baseNum" placeholder="请选择缴纳方式">
            <el-option
              v-for="dict in jiaona"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 如果缴纳方式是按比例缴纳 则显示公司缴纳比例和个人缴纳比例 -->
        <template v-if="form.baseNum == 1">
          <el-form-item label="公司缴纳比例" prop="companyPortion">
            <el-input
              v-model="form.companyPortion"
              placeholder="请输入公司缴纳比例"
            >
              <template #append>%</template>
            </el-input>
          </el-form-item>

          <el-form-item label="个人缴纳比例" prop="personPortion">
            <el-input
              v-model="form.personPortion"
              placeholder="请输入个人缴纳比例"
            >
              <template #append>%</template>
            </el-input>
          </el-form-item>
        </template>

        <!-- 如果缴纳方式是按金额缴纳 则显示公司缴纳金额和个人缴纳金额 -->
        <template v-if="form.baseNum == 2">
          <el-form-item label="公司缴纳金额" prop="companyPay">
            <el-input
              v-model="form.companyPay"
              placeholder="请输入公司缴纳金额"
            >
              <template #prepend>¥</template>
            </el-input>
          </el-form-item>

          <el-form-item label="个人缴纳金额" prop="personPay">
            <el-input v-model="form.personPay" placeholder="请输入个人缴纳金额">
              <template #prepend>¥</template>
            </el-input>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :auto-upload="false"
        :disabled="upload.isUploading"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xlsx、xls格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitFileForm"
            :loading="upload.isUploading"
            >确 定</el-button
          >
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Socialsecurity">
import {
  listSocialsecurity,
  getSocialsecurity,
  delSocialsecurity,
  addSocialsecurity,
  updateSocialsecurity,
  importSocialsecurity,
  getImportTemplate,
} from "@/api/system/socialsecurity";

const rules = {
  project: [{ required: true, message: "请输入缴纳项目", trigger: "blur" }],
  baseNum: [{ required: true, message: "请选择缴纳方式", trigger: "change" }],
  // 按比例缴纳时的校验规则
  companyPortion: [
    { required: true, message: "请输入公司缴纳比例", trigger: "blur" },
    {
      pattern: /^\d+(\.\d{1,2})?$/,
      message: "请输入正确的比例格式",
      trigger: "blur",
    },
  ],
  personPortion: [
    { required: true, message: "请输入个人缴纳比例", trigger: "blur" },
    {
      pattern: /^\d+(\.\d{1,2})?$/,
      message: "请输入正确的比例格式",
      trigger: "blur",
    },
  ],
  // 按金额缴纳时的校验规则
  companyPay: [
    { required: true, message: "请输入公司缴纳金额", trigger: "blur" },
    {
      pattern: /^\d+(\.\d{1,2})?$/,
      message: "请输入正确的金额格式",
      trigger: "blur",
    },
  ],
  personPay: [
    { required: true, message: "请输入个人缴纳金额", trigger: "blur" },
    {
      pattern: /^\d+(\.\d{1,2})?$/,
      message: "请输入正确的金额格式",
      trigger: "blur",
    },
  ],
};

const { proxy } = getCurrentInstance();
const { jiaona } = proxy.useDict("jiaona");

const socialsecurityList = ref([]);
const open = ref(false);
const open1 = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {},
});

const { queryParams, form } = toRefs(data);

// 导入参数
const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  fileList: [], // 添加文件列表存储
});

// 文件上传ref
const uploadRef = ref(null);

/** 查询五险一金设置表列表 */
function getList() {
  loading.value = true;
  listSocialsecurity(queryParams.value).then((response) => {
    socialsecurityList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  open1.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    project: null,
    baseNum: 1,
    basePayment: null,
    companyPortion: null,
    personPortion: null,
    companyPay: null,
    personPay: null,
    accountSetsId: null,
  };
  proxy.resetForm("socialsecurityRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加五险一金设置表";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getSocialsecurity(_id).then((response) => {
    form.value = response.data;
    open1.value = true;
    title.value = "修改五险一金设置表";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["socialsecurityRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateSocialsecurity(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open1.value = false;
          getList();
        });
      } else {
        addSocialsecurity(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

// /** 删除按钮操作 */
// function handleDelete(row) {
//   const _ids = row.id || ids.value;
//   proxy.$modal
//     .confirm('是否确认删除五险一金设置表编号为"' + _ids + '"的数据项？')
//     .then(function () {
//       return delSocialsecurity(_ids);
//     })
//     .then(() => {
//       getList();
//       proxy.$modal.msgSuccess("删除成功");
//     })
//     .catch(() => {});
// }

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/socialsecurity/export",
    {
      ...queryParams.value,
      needTranslate: true, // 添加标识，告诉后端需要转换baseNum字段
    },
    `socialsecurity_${new Date().getTime()}.xlsx`
  );
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "五险一金数据导入";
  upload.open = true;
}

/** 下载模板操作 */
function importTemplate() {
  getImportTemplate().then((res) => {
    const blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
    const link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);
    link.download = "五险一金导入模板.xlsx";
    link.click();
    window.URL.revokeObjectURL(link.href);
  });
}

// 文件状态改变
function handleFileChange(file) {
  upload.fileList = [file];
}

// 文件移除
function handleFileRemove() {
  upload.fileList = [];
}

// 提交上传文件
function submitFileForm() {
  if (!upload.fileList.length) {
    proxy.$modal.msgError("请选择要上传的文件");
    return;
  }
  const formData = new FormData();
  formData.append("file", upload.fileList[0].raw);
  upload.isUploading = true;
  importSocialsecurity(formData)
    .then((res) => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess(res.msg);
        upload.open = false;
        getList();
      } else {
        proxy.$modal.msgError(res.msg);
      }
      upload.isUploading = false;
      upload.fileList = [];
      if (uploadRef.value) {
        uploadRef.value.clearFiles();
      }
    })
    .catch(() => {
      upload.isUploading = false;
    });
}

getList();
</script>

<style scoped>
.el-upload__tip {
  line-height: 20px;
  padding-top: 5px;
  margin-bottom: 0 !important;
}
</style>
